var trs = document.getElementsByTagName("tr");
zonjia();

function zonjia() {
	var zj = 0;
	if (trs.length == 1) {
		$("#zonjia").html("￥" + zj);
	} else {
		for (var i = 1; i < trs.length; i++) {
			zj += parseInt(trs[i].children[3].children[0].innerHTML);
			$("#zonjia").html("￥" + zj);
			//		console.log(trs[i].children[3].children[0].innerHTML);
		}
	}
}

function deleteCurrentRow(obj) {
	var tr = obj.parentNode.parentNode;
	var tbody = tr.parentNode;
	tbody.removeChild(tr);
	zonjia();
	 AV.Query.doCloudQuery('delete from gouwuche where objectId="'+tr.children[0].innerHTML+'"').then(function () {
    // 删除成功
  }, function (error) {
  	console.log(error)
    // 异常处理
  });
}

function goumai() {
	for (var i = 1; i < trs.length; i++) {
		trs[i].children[4].innerHTML = "已购买";
	}
}
window.onload = function() {
	var APP_ID = 'eG22PNfwqck3fDTem41ACiNU-gzGzoHsz';
	var APP_KEY = 'Y8VoXz0cIzsJVbpctUAJXAAh';
	AV.init({
		appId: APP_ID,
		appKey: APP_KEY
	});
	pddenglu();
	var currentUser = AV.User.current();
	updateProduct();
	
}
function pddenglu() {
	currentUser = AV.User.current();
	href = "denglu.html?RetUrl=" + getPageUrl() + "&" + geturl();
	$(".top_a ul li").eq(1).html("<a href=" + href + ">登录</a>")
	if(currentUser) {
		$(".top_a ul li").eq(0).html("欢迎【" + currentUser.attributes.username + "】|");
		$(".top_a ul li").eq(1).html("<a>退出登录</a>");
		$(".top_a ul li").eq(1).bind("click", function() {
			localStorage.clear();
			location.href = location.href;
		})
	}
}

function getPageUrl() {
	var index = location.pathname.lastIndexOf("/") + 1;
	var i = location.pathname.substr(index);
	//			console.log(i)
	return escape(i)
}

function geturl() {
	var u = location.search;
	u = u.substring(1, (u.length))
	console.log(u);
	return u;
}
function updateProduct() {
	// LeanCloud - 查询
	// https://leancloud.cn/docs/leanstorage_guide-js.html#查询
	var query = new AV.Query('gouwuche');
	query.descending('createdAt');

	query.find().then(function(products) {
		for (var i = 0; i < products.length; i++) {
			var divtj = '<tr><td>' + products[i].id + '</td>';
			divtj+='<td>'+products[i].attributes.inid+'</td>';
			divtj += '<td class="tab_img">' + products[i].attributes.image + '<span>' + products[i].attributes.title + '</span></td>';
			divtj += '<td>￥<span>' + products[i].attributes.price + '</span></td>';
			divtj += '<td>带交付</td>';
			divtj += '<td><input class="tabinput" type="button" value="删除" onclick="deleteCurrentRow(this)" /></td>';
			divtj += '</tr>';
			$("#tab").append(divtj);
		}
		var trs = document.getElementsByTagName("tr");
	zonjia();
		// 查询到商品后，在前端展示到相应的位置中

	}).catch(function(error) {
		alert(JSON.stringify(error));
	});

}